package com.scs.application.modules.msg.provider;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.scs.application.core.exceptions.BusinessException;
import com.scs.application.core.msg.domain.RawMessage;
import com.scs.application.core.msg.domain.WechatMessage;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.msg.entity.PushedRecord;
import com.scs.application.modules.msg.exception.SendMessageException;
import com.scs.application.modules.upms.service.UserWxService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description: 微信消息处理
 */
@Component
@AllArgsConstructor
@Slf4j
public class SendWechatMessageProvider implements SendMessageProvider<WechatMessage> {
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private UserWxService userWxService;

    @Override
    public boolean check(WechatMessage message) {
        if (StringUtils.isBlank(message.getLoginKey())) {
            throw new BusinessException("微信消息校验失败，登录账号不能为空");
        }
        if (StringUtils.isBlank(message.getTemplateCode())) {
            throw new BusinessException("微信消息校验失败，模板ID不能为空");
        }
        return true;
    }

    @Override
    public boolean support(Class<? extends RawMessage> clz) {
        return (WechatMessage.class.isAssignableFrom(clz));
    }

    /**
     * 构建pushRecord
     *
     * @param pushedRecord
     * @param wechatMessage
     * @return
     */
    @Override
    public PushedRecord getPushedRecord(PushedRecord pushedRecord, WechatMessage wechatMessage) {
        pushedRecord.setTitle(null)
                .setContent(wechatMessage.getTemplateCode())
                .setReceiver(wechatMessage.getLoginKey())
                .setReceiver(wechatMessage.getLoginKey())
                .setParams(wechatMessage.getParams() != null ? JSONObject.parseObject(JSON.toJSONString(wechatMessage.getParams())) : null);
        return pushedRecord;
    }

    @Override
    public void send(WechatMessage wechatMessage) throws SendMessageException {
        List<String> openIdList = userWxService.getOpenIdByLoginKey(wechatMessage.getLoginKey());
        if (ObjectUtil.length(openIdList) == 0) {
            log.error("【微信模版消息】发送失败，用户标识{}未找到绑定的openId", wechatMessage.getLoginKey());
            return;
        }

        WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
        configStorage.setAppId("wxcd6d85cdb5b19c11");
        configStorage.setSecret("6c48c3b39db6bc4167ed3132a6b8059a");
        wxMpService.setWxMpConfigStorage(configStorage);
        for(String openId : openIdList) {
            WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
            templateMessage.setTemplateId(wechatMessage.getTemplateId());
            templateMessage.setToUser(openId);
            templateMessage.setUrl(wechatMessage.getToUrl());
            templateMessage.setData(wechatMessage.getData());
            try {
                wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
            }catch (WxErrorException e) {
                log.error("【微信模版消息】发送失败, {}", e);
                throw new SendMessageException(e.getMessage());
            }
        }

    }
}
